package com.top10.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.top10.bean.JwtUtil;
import com.top10.bean.PageBean;
import com.top10.bean.ResponseBean;
import com.top10.common.Const;
import com.top10.entity.Coupon;
import com.top10.entity.CouponUser;
import com.top10.entity.Shop;
import com.top10.entity.User;
import com.top10.entity.vo.CouponVo;
import com.top10.service.*;
import com.top10.utils.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author sny
 * @Package com.top10.controller.mobile
 * @date 2018/10/1
 */
@RestController
@RequestMapping("/top10/coupon/manager")
public class CouponController {

    @Autowired
    IUserService userService;

    @Autowired
    private ICouponService iCouponService;


    @Autowired
    private ICouponGoodsService iCouponGoodsService;

    @Autowired
    private ICouponShopService iCouponShopService;

    @Autowired
    private ICouponUserService iCouponUserService;
    @Autowired
    IShopService shopService;


    /**
     * 商品优惠券
     * @param goodsuuid
     * @return
     */
    @PostMapping("/goodscoupon")
    public ResponseBean goodscoupon(String goodsuuid)throws Exception{

        List list = new ArrayList();
        List<Map<String, Object>> goodscoupon=iCouponGoodsService.selectgoodscoupon(goodsuuid);
        if(goodscoupon.size()!=0){
            for(Map<String,Object> map : goodscoupon){
                Object amount=map.get("amount");
                list.add(amount);
            }
            Object amount1=Collections.min(list);
            return ResponseBean.createSuccess().addData("goodscoupon",goodscoupon).addData("amount",amount1);
        }
        return ResponseBean.createSuccess("没有优惠卷").addData("goodscoupon",goodscoupon);
    }

    /**
     * 用户领取优惠券
     *
     * @param
     * @return
     * @throws ParseException
     */
    @PostMapping("/getgoodscoupon")
    public ResponseBean goodscoupon(String  couponuuid, HttpServletRequest request) throws ParseException {

        if(couponuuid==null){
            return ResponseBean.createError("couponuuid不能为空");
        }
        Coupon coupon=iCouponService.selectOne(new EntityWrapper<Coupon>().eq("uuid",couponuuid));
        if(coupon==null){
            return  ResponseBean.createError("不存在该优惠券");
        }

//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//        Date date = dateFormat.parse(coupon.getEndDate());
//
//        if(date.getTime() < new Date().getTime()){
//            return ResponseBean.createError("该优惠券已经过期");
//        }

        if(coupon.getCouponNum().intValue()<=0){

            return ResponseBean.createError("该优惠券被抢光了");
        }

        //        String token = request.getHeader(WebConst.TOKEN);
//        String temp = jwtUtil.parseJwtPayload(token);
//       JSONObject obj = JSONObject.fromObject(temp);
//        System.out.println(obj.getString("sub"));

        String userUuid = JwtUtil.getUuidByToken(request);
        User user = userService.selectOne(new EntityWrapper<User>().eq("uuid", userUuid));

        CouponUser couponUsers=iCouponUserService.selectOne(new EntityWrapper<CouponUser>().eq("userId",user.getUuid())
                .eq("couponId",coupon.getId()));
        if(couponUsers!=null){
            return ResponseBean.createError("用户已经领取过该优惠券");
        }
        CouponUser couponUser=new CouponUser();
        couponUser.setCouponId(coupon.getId().toString());
        couponUser.setIsUsed("0");
        couponUser.setReceiveDate(new Date());
        couponUser.setUserId(user.getUuid());
        couponUser.setUuid(RandomUtils.makeUUID());

        boolean result=couponUser.insert();


        if(result==true){

            coupon.setCouponNum(coupon.getCouponNum()-1);
            iCouponService.updateById(coupon);

            return ResponseBean.createSuccess().setMessage("领取成功");
        }
        else{
            return ResponseBean.createError("领取失败");
        }



    }

    /***
     * 新的店铺的优惠券接口h
     * @param shopuuid
     * @return
     */

    @PostMapping("/shopcouponone")
    public ResponseBean shopcoupon(HttpServletRequest request,String shopuuid,BigDecimal requirementAmount) {
        String userUuid = JwtUtil.getUuidByToken(request);
        User user = userService.selectOne(new EntityWrapper<User>().eq("uuid", userUuid));
        List list = new ArrayList();
        List<Map<String, Object>> goodscoupon = iCouponGoodsService.selectshopcoupon(shopuuid,requirementAmount);
            List<CouponVo> goodscoupon1=iCouponGoodsService.selectgoodscoupon0ne(shopuuid,requirementAmount);
            for(CouponVo couponVo: goodscoupon1) {
                CouponUser couponUsers = iCouponUserService.selectOne(new EntityWrapper<CouponUser>().eq("userId", user.getUuid())
                        .eq("couponId", couponVo.getCid()));
                if (couponUsers == null) {
                    CouponUser couponUser = new CouponUser();
                    couponUser.setCouponId(couponVo.getCid().toString());
                    couponUser.setIsUsed("0");
                    couponUser.setReceiveDate(new Date());
                    couponUser.setUserId(user.getUuid());
                    couponUser.setUuid(RandomUtils.makeUUID());

                    boolean result = couponUser.insert();


                    if (result == true) {
                        Coupon coupon=new Coupon();
                        coupon.setCouponNum(couponVo.getCouponNum() - 1);
                        coupon.setId(couponVo.getCid());
                        coupon.setAmount(couponVo.getAmount());
                        coupon.setUuid(couponVo.getCuuid());
                        coupon.setStartDate(couponVo.getStartDate());
                        coupon.setEndDate(couponVo.getEndDate());
                        coupon.setRequirementAmount(couponVo.getRequirementAmount());
                        iCouponService.updateById(coupon);
                    }
                }
            }
        if (goodscoupon.size()!=0) {
            for (Map<String, Object> map : goodscoupon) {
                Object amount = map.get("amount");
                list.add(amount);
            }
            Object amount1 = Collections.min(list);
            return ResponseBean.createSuccess().addData("goodscoupon", goodscoupon).addData("amount", amount1);
        }


        return ResponseBean.createSuccess("该商店没有优惠卷").addData("goodscoupon", goodscoupon);
    }
    /***
     * 店铺的优惠券h
     * @param shopuuid
     * @return
     */

    @PostMapping("/shopcoupon")
    public ResponseBean shopcoupon(String shopuuid) {
        List list = new ArrayList();
        List<Map<String, Object>> goodscoupon = iCouponGoodsService.selectshopcoupontwo(shopuuid);
        if (goodscoupon.size()!=0) {
            for (Map<String, Object> map : goodscoupon) {
                Object amount = map.get("amount");
                list.add(amount);
            }
            Object amount1 = Collections.min(list);
            return ResponseBean.createSuccess().addData("goodscoupon", goodscoupon).addData("amount", amount1);
        }
        return ResponseBean.createSuccess("该商店没有优惠卷").addData("goodscoupon", goodscoupon);
    }


//
//    @PostMapping("/test")
//    public ResponseBean test(HttpServletRequest request) {
//
//        String data = request.getParameter("OrderCreate");
//
//        Gson gson = new Gson();
//
//        List<Coupon> coupons = gson.fromJson(data, new TypeToken<List<Coupon>>() {}.getType());
//
//        for (Coupon coupon : coupons) {
//
//            System.out.println(coupon.getCouponName());
//            System.out.println(coupon.getAmount());
//            //return ResponseBean.createSuccess().addData("coupon",coupon);
//        }
//        return ResponseBean.createError("dssf");
//    }

    @PostMapping("/couponnumber")
    public  ResponseBean getcouponnumber(HttpServletRequest request,PageBean pageBean){


//        String token = request.getHeader(WebConst.TOKEN);
//        String temp = jwtUtil.parseJwtPayload(token);
//       JSONObject obj = JSONObject.fromObject(temp);
//        System.out.println(obj.getString("sub"));


        String userUuid = JwtUtil.getUuidByToken(request);
      //String userUuid = "2c5006a745b1444a8d35eebb50e44960";
//        User user = userService.selectOne(new EntityWrapper<User>().eq("uuid", userUuid));
//
//        Integer couponnumber=iCouponUserService.selectCount(new EntityWrapper<CouponUser>().eq("userId",user.getUuid()));
//
//        return ResponseBean.createSuccess().addData("couponnumber",couponnumber);

        User user = userService.selectOne(new EntityWrapper<User>().eq("uuid", userUuid));

        Page page= PageHelper.startPage(pageBean.getPageNum(),pageBean.getPageSize());
        List<Map<String,Object>> coupons=iCouponService.couponNotUser(user.getUuid(),2);

        pageBean=new PageBean(pageBean.getPageNum(),pageBean.getPageSize(), (int) page.getTotal());
        return ResponseBean.createSuccess()
                .addData("couponnumber",pageBean.getCount());


    }


    @PostMapping("/selectnotusecoupon")
    public ResponseBean getnotusecoupon(long type,PageBean pageBean,HttpServletRequest request){


//        String token = request.getHeader(WebConst.TOKEN);
//        String temp = jwtUtil.parseJwtPayload(token);
//       JSONObject obj = JSONObject.fromObject(temp);
//        System.out.println(obj.getString("sub"));

     String userUuid = JwtUtil.getUuidByToken(request);
   //   String userUuid = "2c5006a745b1444a8d35eebb50e44960";
        User user = userService.selectOne(new EntityWrapper<User>().eq("uuid", userUuid));

        Page page= PageHelper.startPage(pageBean.getPageNum(),pageBean.getPageSize());
        List<Map<String,Object>> coupon=iCouponService.couponNotUser(user.getUuid(),type);

        pageBean=new PageBean(pageBean.getPageNum(),pageBean.getPageSize(), (int) page.getTotal());
        return ResponseBean.createSuccess().addData("coupon",coupon)
                .addData("pageBean",pageBean);

    }

    @PostMapping("/listCoupon")
    public ResponseBean listCoupon(HttpServletRequest request){
        return null;
    }


}